
<template>
  <massif-layout leftWidth="300px" :showBack="true" @back="goBack">
      <template v-slot:left>
          <div class="receive-land-left-view">
              <div class="mass-view">
                  <div class="name">已选地块 <span style="color: #00b070;font-size:15px;">({{selectLandList.length}})</span></div>
                  <div style="color: #00b070;font-size:14px;">{{getMapSize}}(亩)</div>
              </div>
              <div>
                  <div> 
                      <el-input placeholder="搜索地块名称" clearable v-model="sreachText" >
                          <template #append>
                              <vxe-icon name="search" size="mini"></vxe-icon>
                          </template> 
                      </el-input>
                  </div>
                  <div class="filter-view">
                      <el-select v-model="selectText"  style="width:120px;" clearable placeholder="全部">
                          <el-option v-for="item in groupList" :label="item.groupName" :value="item.landGroupId"></el-option>
                      </el-select>
                       <vxe-button mode="text" v-if="showFooter" @click="btnAllDel"  icon="vxe-icon-delete" size="small" status="danger" content="清空"></vxe-button>
                  </div>
                  <landList :tableData="getLandTable" :showDel="showFooter" @onClick="setMapData" @onDelete="delCell" />
              </div>
          </div>
      </template>
      <div class="right-view-map">
         <vxe-button mode="text" size="small" 
         @click="btnBack" 
         v-if="showFooter" 
         style="position: absolute;top:10px;right:10px;z-index:999;" 
         icon="vxe-icon-arrow-left">返回</vxe-button>

        <mapContainer 
            @init="initMap" 
            @zoom="zoomMap" 
            :searchPanel="false" 
            @click="clickMap"  
            @pointerMove="pointerMove" />
          <div class="groug-change-view" style="bottom:150px;">
            <el-select v-model="landType"
            @change="changeLandType"
            size="small" style="width:100px;" 
                clearable placeholder="地块类型">
              <el-option
                v-for="item in landTypeList"
                :key="item.landTypeId"
                :label="item.landTypeName"
                :value="item.landTypeId">
              </el-option>
            </el-select>
          </div>
          <div class="groug-change-view">
            <div class="groug-list">
                <div class="item on">已选地块</div>
                <div class="item">未选地块</div>
            </div>
          </div>
          <div class="groug-view">
            <div class="groug-list">
                <div class="item"
              @click="btnChooseGroug('')"
              :class="landGroupId==''?'on':''">全部地块</div>
              <div class="item"
              v-for="item in groupList"
              @click="btnChooseGroug(item)"
              :class="item.landGroupId==landGroupId?'on':''">{{item.groupName }}</div>
            </div>
          </div>
          <div class="groug-right-view" v-if="showFooter">
            <div>提示：点击选择或切换分组来选择地块</div>
            <div class="choose-land">
                <el-checkbox v-model="checkedLand" @change="changeCheckBox"></el-checkbox> 全选地块
            </div>
            <vxe-button mode="text" 
            status="primary" 
            size="small" 
            @click="saveLand"
            :content="`确定 (${selectLandList.length})`" icon="vxe-icon-check"></vxe-button>
          </div>
      </div>
      <PoiPopup v-if="showPop &&currentZoom>12" :popOption="popObjct"   @onClose="(type)=>{showPop=type}" />
  </massif-layout>
</template>

<script setup>  
import { nextTick, ref, watch, onActivated,reactive,onMounted,computed} from 'vue'
import{useRouter,useRoute} from "vue-router"
import {getLandList,getLandGroupList,getLandTypeList} from '@/api/plant'
import {getMinLandList,getGenerate} from '@/api/plant'
import {message} from '@/utils/element'
import massifLayout from '../components/layout.vue'
import groupSelect from '@/components/custom/groupSelect.vue'
import landSelect from '@/components/custom/landSelect.vue'
import cDialog from '@/components/custom/cDialog.vue'
import { useUserStore } from '@/pinia/modules/user'
import cropSelect from '@/components/custom/cropSelect.vue'
import Image from '@/components/custom/image.vue'
import CountUp from 'vue-countup-v3'
import landList from './components/landList.vue'
import  mapContainer from '@/components/Map/index.vue'
import {WktToPolygon } from '@/components/Map/utils/geoToWkt';
import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer"
import Graphic from "@arcgis/core/Graphic"
import * as webMercatorUtils from "@arcgis/core/geometry/support/webMercatorUtils.js";
import PoiPopup from '@/components/Map/components/PoiPopup.vue';
import Point from '@arcgis/core/geometry/Point.js';
import {VXETable} from 'vxe-table'
const emit = defineEmits(['close','change','complete'])
const router = useRouter()
const userStore = useUserStore()
const dropFarmLandId = ref('')
const dropFarmLandNo = ref('') 
const dropFarmLandPic = ref('') 
const tableData = ref([])
const selectLandList = ref([])
const currentZoom= ref(5)
const clickRow = ref(null)
const showPop = ref(false)
const checkedLand = ref(false)
const sreachText = ref('')
const selectText = ref('')
const groupList = ref('')
const landGroupId = ref('')
const popObjct = ref({})
const landTypeList = ref([])
const landType = ref('')
const loadingCount = ref(1)

let mapView =null
let graphicsLayer = null

const props = defineProps({
  dataList: {
  type: Array,
  default: []
},
selectList: {
  type: Array,
  default: []
},
openCount:{
  type: Number,
  default: 1
},
showFooter:{
  type: Boolean,
  default: true
}
})

watch(()=>props.selectList,(n,o)=>{
  if(props.selectList.length>0){
      if(props.showFooter){
        selectLandList.value =props.selectList
        changeLandColor() 
      }else{
        setTableList()
      }
  }else{
    selectLandList.value =[]
    checkedLand.value=false
    changeLandColor()
  }
})

const setTableList = ()=>{
  selectLandList.value =props.selectList
      if(graphicsLayer){
       const graphics = graphicsLayer.graphics.items.filter(item => item.attributes.type != 'text')
         graphics.forEach(item => {
          if(props.selectList.includes(item.attributes.farmLandId)){
            item.visible =true
          }else{
            item.visible =false
          }
         })
       }
       changeLandColor()
}

const getLandTable =computed(()=>{
  if(sreachText.value!='' && selectText.value!=''){
    return tableData.value.filter((item)=>{
    return selectLandList.value.includes(item.farmLandId) && item.farmLandName.indexOf(sreachText.value)>=0 && item.landGroupId==selectText.value
    })
  }
  if(sreachText.value!=''){
    return tableData.value.filter((item)=>{
      return selectLandList.value.includes(item.farmLandId) &&  item.farmLandName.indexOf(sreachText.value)>=0
   })
  }
  if(selectText.value!=''){
    return tableData.value.filter((item)=>{
      return selectLandList.value.includes(item.farmLandId) &&  item.landGroupId==selectText.value
    })
  }
  return tableData.value.filter((item)=>{
    return selectLandList.value.includes(item.farmLandId)
  })
})

const getLandData =async ()=>{
let res = await getMinLandList({
        page:1,
        limit:1,
        farmId:userStore.userInfo.farmId,
        // farmLandStatus:0,
        companyId:userStore.userInfo.companyId
     })
  if(res.success){
    getLandTimes(res.total||1)
  }else{
    message('出错了', 3)
  }
}

const getLandTimes =async (farmLandCount)=>{
    let limit=500
     let params ={
      farmId:userStore.userInfo.farmId, 
      // farmLandStatus:0,
      companyId:userStore.userInfo.companyId}
        if(farmLandCount>0){
          let pageStr = (farmLandCount/limit).toFixed(3)
          let totalPage =0
          let page1 = pageStr.split('.')[0]
          let page2 = pageStr.split('.')[1]
          let pages =[]
          if(Number(page2)>0){
            totalPage = Number(page1)+1
          }
          for(let i=1;i<=totalPage;i++){
            pages.push({page:i,limit:limit})
          }
          pages.forEach(async (item)=>{
            setTimeout(async () => {
              let res =await getMinLandList({...params,...item})
              if(res.success){
                 drawLandList(res.data||[])
                 tableData.value= tableData.value.concat(res.data||[])
                 emit('complete',tableData.value)
              }  
            }, item.page==1?0:(item.page*1000));
      })
  }
}

const initMap = (map)=>{
     mapView = map
    getLandData()
    getLandGroupList({farmId:userStore.userInfo.farmId}).then((res)=>{
        if(res.success){
          groupList.value = res.data ||[]
      }
     })
     getLandTypeList({farmId:userStore.userInfo.farmId}).then((res)=>{
        if(res.success){
          landTypeList.value = res.data ||[]
      }
     })
     
}

const btnChooseGroug =(row)=>{
  landGroupId.value =row?.landGroupId||''
  if(landGroupId.value){
    let list1=  tableData.value.filter((item)=>{return item.landGroupId == landGroupId.value})
    let list2= selectLandList.value.filter((item)=>{return item.landGroupId == landGroupId.value})
    checkedLand.value =list1.length ==list2.length
  }else{
      checkedLand.value =tableData.value.length ==selectLandList.value.length
  }
  let graphics =[]
   if(graphicsLayer){
      if(landType.value){
        graphics = graphicsLayer.graphics.items.filter(item => item.attributes.type != 'text' && item.attributes.landTypeId == landType.value )
      }else{
        graphics = graphicsLayer.graphics.items.filter(item => item.attributes.type != 'text')
      }
      graphics.forEach(item => {
          if(item.attributes.landGroupId == landGroupId.value || landGroupId.value==''){
              item.visible =true
          }else{
              item.visible =false
          }
      })
      mapView.goTo(graphics.filter((item)=>{return item.attributes.landGroupId==landGroupId.value|| landGroupId.value==''}));
   }
}

const  changeLandType =(val)=>{
  if(graphicsLayer){
      let graphics =[]
        if(landGroupId.value){
           graphics = graphicsLayer.graphics.items.filter(item =>{return  item.attributes.type != 'text' &&item.attributes.landGroupId==landGroupId.value})
        }else{
           graphics = graphicsLayer.graphics.items.filter(item => item.attributes.type != 'text')
        }
      graphics.forEach(item => {
        if(item.attributes.landTypeId == val ||val==''){
          item.visible =  true 
        }else{
          item.visible =  false 
        }
      })
   }
}

const changeCheckBox =(val)=>{
    let graphics =[]
    if(val){
       graphics = graphicsLayer.graphics.items.filter(item =>{return  item.visible}).map((item)=>item.attributes.farmLandId)
       selectLandList.value =Array.from(new Set(selectLandList.value.concat(graphics)));
    }else{
      //补集
      graphics = graphicsLayer.graphics.items.filter(item =>{return  item.visible}).map((item)=>item.attributes.farmLandId)
        let select = selectLandList.value
      selectLandList.value = select.filter(function(v){ return !(graphics.indexOf(v) > -1) }).concat(graphics.filter(function(v){ return !(select.indexOf(v) > -1)}))
    }
    changeLandColor()
}

const saveLand =()=>{
  emit('change',{selects:getLandTable.value.map((item)=>item.farmLandId),total:getMapSize.value})
  btnBack()
}


const getMapSize = computed(()=>{
  let totalSize=0
  getLandTable.value.forEach((item)=>{
      totalSize+=item?.mapAreaSize||0
  })
  return totalSize.toFixed(1)
})


const getLandDataList = computed(()=>{
  if(sreachText.value!='' && selectText.value!=''){
      return selectLandList.value.filter((item)=>{return item.farmLandName.indexOf(sreachText.value)>=0 && item.landGroupId==selectText.value})
  }
  if(sreachText.value!=''){
      return selectLandList.value.filter((item)=>{return item.farmLandName.indexOf(sreachText.value)>=0})
  }
  if(selectText.value!=''){
      return selectLandList.value.filter((item)=>{return item.landGroupId==selectText.value})
  }
  return selectLandList.value
})


const zoomMap=(val)=>{
  currentZoom.value = val
  if(graphicsLayer){
        const graphics = graphicsLayer.graphics.items.filter(item => item.attributes.type == 'text')
        graphics.forEach(item => {item.visible = val > 17 ? true : false})
  }
  getClickData()
}

const pointerMove=(val)=>{
 getClickData()
}


//选中-地块改变颜色
const changeLandColor =()=>{
      if (graphicsLayer) {
          graphicsLayer.graphics.items.forEach((item) =>{
            if(selectLandList.value.includes(item.attributes.farmLandId)){
              item.symbol = {
                      type: 'simple-fill',
                      color:'#25c289',
                      outline: {
                          color: '#25c289',
                          width: 1
                      }
              }
            }else{
              item.symbol = {
                      type: 'simple-fill',
                      color:'#25c28900',
                      outline: {
                          color: '#25c289',
                          width: 1
                      }
              }
            }
          })
   }
}

const delCell=(index)=>{
  selectLandList.value.splice(index,1)
  changeLandColor()
}

const btnAllDel =()=>{
  selectLandList.value=[]
  changeLandColor()
  btnChooseGroug({landGroupId:landGroupId.value})
}

const clickMap =(e,e2)=>{
    if(!props.showFooter){return}
    if(e2.results.length>0){
        e2.results.forEach(e3 => {
        let attrs = e3.graphic.attributes
       if(attrs?.class == "click-landMark") { 
         let data = selectLandList.value.filter((item)=>item.farmLandId == attrs.farmLandId)
         if(data){
          let b = [attrs.farmLandId]
          selectLandList.value= selectLandList.value.filter(function(v){ return !(b.indexOf(v) > -1) }).concat(b.filter(function(v){ return !(selectLandList.value.indexOf(v) > -1)}))
         }else{
          selectLandList.value.push(attrs.farmLandId)
         }
         changeLandColor()
        }
      })
    }
}

//地块绘制到地图
const drawLandList = (dataList)=>{
  if(!graphicsLayer){
    graphicsLayer = new GraphicsLayer({ id:'select-land-plot'});
  }else{
    //graphicsLayer.removeAll()
  }
  dataList.forEach((item,index)=>{
    if(item?.geom){
        const geo = WktToPolygon(item.geom, { wkid: 4326 });
        const newGeo = webMercatorUtils.geographicToWebMercator(geo)
        const polygon = new Graphic({
          geometry: newGeo,
          symbol: {
            type: 'simple-fill',
            color:'#25c28900',
            outline: {
                color: '#25c289',
                width: 1
            }
          },
          attributes: {
            class: 'click-landMark',
            farmLandId:item.farmLandId,
            ...item
          }
          })
          const textAreaStyle = {
              type: "text", 
              color: [255, 255, 255],
              haloColor: [0, 0, 0],
              haloSize: "1px",
              text: "",
              xoffset: 0,
              yoffset: 0,
              cursor: 'pointer',
              font: {
                size: 10,
                family: "PingFangSC",
                weight: "bold"
              }
          }
          const AreaGeometry = polygon.geometry.extent.center
          const areaValue = Number(item.mapAreaSize.toFixed(1))
          let result = "";
          for (let i = 0, len = item.farmLandName.length; i < len; i++) {
            if (i % 8 === 0 && i != 0) result += '\n';
            result += item.farmLandName[i];
            }
          textAreaStyle.text = `${result}\n${areaValue}亩`
          const textAttr = { ...item, type: 'text' }
          const textAreaGraphic = new Graphic({
              geometry: AreaGeometry,
              symbol: textAreaStyle,
              attributes: textAttr,
              visible: currentZoom.value>17?true:false
            })
            graphicsLayer.add(polygon);
            graphicsLayer.add(textAreaGraphic)
            mapView.map.add(graphicsLayer)
    }
  })

  if(!props.showFooter){
      setTableList()
  }
  if(loadingCount.value==1){
    //定位
    loadingCount.value = 2
    setTimeout(() => {
        mapView.goTo(graphicsLayer.graphics.items);
        // changeLandColor()
    }, 500);
  }
}

// 设置选中高亮
const setSelectLine = ({ row, rowIndex }) =>{
  if(row.farmLandId == dropFarmLandId.value){
      return "selectedStyle"
  }else{
      return ''
  }
}


//点击坐标点的弹出框数据
const getClickData = ()=>{
if(!clickRow.value){return}
let item = clickRow.value
const mapPoint = new Point({longitude: item.locationLongitude,latitude: item.locationLatitude, spatialReference: {wkid: 4326}});
 const { x, y } = mapView.toScreen(mapPoint)
 item.x = x
 item.y = y
const popOption = {
          title:item.farmName||item.farmLandNo,
          farmId:item.farmId,
          companyId:item.companyId,
          farmLandId:item.farmLandId,
          pic:item.pic,
          screenX: item.x+10,
          screenY: item.y+10,
          visible:true,
          mapX: item.longitude,
          mapY: item.latitude,
          btnText:'地块详情',
          values: [
              // {
              //     label: '所属农场',
              //     value: item.farmName
              // },
              {
                  label: '地块编号',
                  value: item.farmLandNo
              },
              {
                  label: '地块名称',
                  value: item.farmLandName
              },
              {
                  label: '地块面积',
                  value:  Number(item.mapAreaSize.toFixed(1))+'亩'
              },
              {
                  label: '位置',
                  value: item.locationAddress
              }
          ],
          ...item
}
popObjct.value = popOption
}
// 表格行单击处理事件
const setMapData = (row)=>{
  dropFarmLandId.value = row.farmLandId
  dropFarmLandPic.value = row.pic
  dropFarmLandNo.value = row.farmLandNo
  setSelectLine({row})
  const graphics = graphicsLayer.graphics.items.filter((m) => m.attributes.farmLandId == row.farmLandId)
  mapView.goTo(graphics);
  clickRow.value = row
  showPop.value = true
  getClickData()
}

const btnBack = ()=>{
  emit('close')
}

const mapLocation = ()=>{
  if(mapView){
    mapView.goTo(graphicsLayer.graphics.items);
  }
}
defineExpose({mapLocation})

</script>
<style>
.filter-view .el-select .el-input__inner{
  background-color: #f5f7fa;
}
</style>
<style lang="scss" scoped>
.receive-land-left-view{
      box-sizing: border-box;
      display: flex;
      flex-flow: column;
      height: 100%;
      padding: 0;
      //overflow: hidden;
      .mass-view{
          display: flex;
          justify-content: space-between;
          padding: 6px 10px;
          border-bottom: 1px solid #ddd;
          margin-bottom: 10px;
          .name{
              font-size:15px;
              font-weight: bold;
              color: #333;
              position: relative;
              &::after{
                  position: absolute;
                  contain: '';
                  content:'';
                  height:16px;
                  width:2px;
                  background-color: #04AE70;
                  left: -5px;
              }
          }
      }
    .filter-view{
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #f5f7fa;
        padding:6px 0;
        .el-input__inner{
          background-color: #f5f7fa;
        }
    }
}


.right-view-map{
  height: calc(100vh - 115px);
  position: relative;
  width:100%;
  .groug-change-view{
      position: absolute;
      bottom:60px;
      left:10px;
      z-index:99; 
      border:1px solid #a9a8a8;
      .groug-list{
          background-color: #00000080;
          .item{
              height:36px;
              line-height:36px;
              padding:0 10px;
              font-size:13px;
              color: #fff;
              position: relative;
              text-indent: 25px;
          }::after{
             position: absolute;
             height:10px;
             width:20px;
             border:1px solid #04AE70;
             content: '';
             left:5px;
             top:50%;
             margin-top:-5px;
             
          }.on::after{
              background-color:#04AE70;
          }
      }
  }
  .groug-right-view{
      position: absolute;
      bottom:20px;
      right:80px;
      z-index:99; 
      border:1px solid #a9a8a8;
      background-color: #00000080;
      padding:12px 20px;
      font-size:15px;
      color: #fff;
      text-align: center;
      .choose-land{
          margin: 8px 0px;
          color: #fff;
          display: flex;
          align-items: center;
          justify-content: center;
      }
  }
 .groug-view{
      position: absolute;
      bottom:10px;
      left:10px;
      z-index:99;
      .groug-list{
          background-color: #fff;
          display: flex;
          justify-content: flex-start;
          .item{
              height:36px;
              line-height:36px;
              padding:0 12px;
              font-size:14px;
              cursor: pointer;
          }.on{
              background-color: #04AE70;
              color:#fff;
          }
      }
 }
}
</style>
